﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.ToolPositioningInternal.CUiTPIGenerateContoursDatasetWindow
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using Newtonsoft.Json;
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Markup;
using System.Xml.Serialization;
using Tecnomatix.Engineering;
using Tecnomatix.Engineering.Ui.WPF;


namespace DnProcessSimulateCommands.ToolPositioningInternal;

public class CUiTPIGenerateContoursDatasetWindow : TxWindow, IComponentConnector
{
  private readonly CApTPIContoursViewModel _viewModel;
  internal System.Windows.Controls.ComboBox labelName;
  internal System.Windows.Controls.ComboBox assemblyComponentType;
  internal System.Windows.Controls.TextBox contoursCount;
  internal System.Windows.Controls.TextBox contourDepth;
  internal System.Windows.Controls.CheckBox isTool;
  internal System.Windows.Controls.DataGrid myDataGrid;
  private bool _contentLoaded;

  public CUiTPIGenerateContoursDatasetWindow()
  {
    this.InitializeComponent();
    this._viewModel = new CApTPIContoursViewModel();
    ((FrameworkElement) this).DataContext = (object) this._viewModel;
    TxApplication.ActiveSelection.Changed += new TxSelection_ChangedEventHandler(this.ActiveSelection_Changed);
    this._viewModel.RefreshButtonState(this.myDataGrid.SelectedItems.Count, this.SelectedApplicationObjects.Count);
    this.RestoreStringCollectionData("LabelsData", this._viewModel.LabelsData);
    this.RestoreStringCollectionData("AssemblyComponentData", this._viewModel.AssemblyComponentData);
  }

  private void StoreStringCollectionData(string regName, ObservableCollection<string> data)
  {
    using (MemoryStream memoryStream = new MemoryStream())
    {
      using (StreamReader streamReader = new StreamReader((Stream) memoryStream))
      {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof (List<string>), new Type[0]);
        List<string> o = new List<string>((IEnumerable<string>) data);
        xmlSerializer.Serialize((Stream) memoryStream, (object) o);
        memoryStream.Position = 0L;
        string end = streamReader.ReadToEnd();
        TxWindowSettings.StoreWindowValue((TxWindow) this, regName, (object) end);
      }
    }
  }

  private void RestoreStringCollectionData(string regName, ObservableCollection<string> data)
  {
    object obj = (object) null;
    TxWindowSettings.RestoreWindowValue((TxWindow) this, regName, ref obj);
    if (obj == null)
      return;
    using (Stream stream = (Stream) new MemoryStream())
    {
      using (StreamWriter streamWriter = new StreamWriter(stream))
      {
        streamWriter.Write(obj as string);
        streamWriter.Flush();
        stream.Position = 0L;
        if (!(new XmlSerializer(typeof (List<string>), new Type[0]).Deserialize(stream) is List<string> stringList))
          return;
        stringList.ForEach((Action<string>) (x => data.Add(x)));
      }
    }
  }

  private void BrowseButton_Click(object sender, RoutedEventArgs e)
  {
    using (SaveFileDialog saveFileDialog = new SaveFileDialog())
    {
      saveFileDialog.Filter = "CSV files|*.csv";
      saveFileDialog.InitialDirectory = Environment.SpecialFolder.Desktop.ToString();
      if (saveFileDialog.ShowDialog() != DialogResult.OK)
        return;
      this._viewModel.DestinationFileName = saveFileDialog.FileName;
    }
  }

  private void Start_Click(object sender, RoutedEventArgs e) => this._viewModel.StartGenerate();

  private void Stop_Click(object sender, RoutedEventArgs e) => this._viewModel.StopGenerate();

  private void SaveState_Click(object sender, RoutedEventArgs e)
  {
    var data = new
    {
      File = this._viewModel.DestinationFileName,
      Data = this._viewModel.ObjectsData.Select(lbl => new
      {
        Name = lbl.Object.Name,
        Label = lbl.Label,
        AssemblyComponentType = lbl.AssemblyComponentType,
        NumberOfContours = lbl.NumberOfContours,
        ContourDepth = lbl.ContourDepth,
        IsTool = lbl.IsTool
      }).ToList()
    };
    File.WriteAllText(TxApplication.InstallationDirectory + "//ContoursTrainingSet.json", JsonConvert.SerializeObject((object) data, (Formatting) 1));
  }

  private void RestoreState_Click(object sender, RoutedEventArgs e)
  {
    try
    {
      string str = File.ReadAllText(TxApplication.InstallationDirectory + "//ContoursTrainingSet.json");
      var data1 = new
      {
        File = "",
        Data = new \u003C\u003Ef__AnonymousType0<string, string, string, int, double, bool>[1]
        {
          new
          {
            Name = "",
            Label = "",
            AssemblyComponentType = "",
            NumberOfContours = 0,
            ContourDepth = 0.0,
            IsTool = false
          }
        }.ToList()
      };
      var data2 = JsonConvert.DeserializeAnonymousType(str, data1);
      this._viewModel.DestinationFileName = data2.File;
      TxObjectList allDescendants = TxApplication.ActiveDocument.PhysicalRoot.GetAllDescendants((ITxTypeFilter) new TxTypeFilter(typeof (ITxComponent)));
      foreach (var data3 in data2.Data)
      {
        ITxComponent objectByName = this.GetObjectByName(data3.Name, allDescendants);
        this._viewModel.ObjectsData.Add(new CApTPILabelData()
        {
          Object = (ITxObject) objectByName,
          Label = data3.Label,
          AssemblyComponentType = data3.AssemblyComponentType,
          NumberOfContours = data3.NumberOfContours,
          ContourDepth = data3.ContourDepth,
          IsTool = data3.IsTool
        });
      }
    }
    catch (Exception ex)
    {
    }
  }

  private void InsertSelection_Click(object sender, RoutedEventArgs e)
  {
    string text1 = this.labelName.Text;
    string text2 = this.assemblyComponentType.Text;
    int result1 = 1;
    int.TryParse(this.contoursCount.Text, out result1);
    double result2 = 1.0;
    double.TryParse(this.contourDepth.Text, out result2);
    if (!string.IsNullOrEmpty(text1) && !this._viewModel.LabelsData.Contains(text1))
      this._viewModel.LabelsData.Add(text1);
    if (!string.IsNullOrEmpty(text2) && !this._viewModel.AssemblyComponentData.Contains(text2))
      this._viewModel.AssemblyComponentData.Add(text2);
    TxObjectList filteredItems = TxApplication.ActiveSelection.GetFilteredItems((ITxTypeFilter) new TxTypeFilter(typeof (ITxComponent)));
    if (((Collection<ITxObject>) filteredItems).Count > 0)
    {
      foreach (ITxComponent itxComponent in (Collection<ITxObject>) filteredItems)
        this._viewModel.ObjectsData.Add(new CApTPILabelData()
        {
          Object = (ITxObject) itxComponent,
          Label = text1,
          AssemblyComponentType = text2,
          NumberOfContours = result1,
          ContourDepth = result2,
          IsTool = this.isTool.IsChecked.Value
        });
    }
    else
    {
      List<CApTPILabelData> selectedItems = this.SelectedItems;
      if (selectedItems.Count <= 0)
        return;
      foreach (CApTPILabelData capTpiLabelData1 in selectedItems)
      {
        CApTPILabelData selectedItem = capTpiLabelData1;
        CApTPILabelData capTpiLabelData2 = this._viewModel.ObjectsData.FirstOrDefault<CApTPILabelData>((Func<CApTPILabelData, bool>) (x => x == selectedItem));
        if (capTpiLabelData2 != null)
        {
          if (text1 != "")
            capTpiLabelData2.Label = text1;
          if (this.contoursCount.Text != "")
            capTpiLabelData2.NumberOfContours = result1;
          if (text2 != "")
            capTpiLabelData2.AssemblyComponentType = text2;
          if (this.contourDepth.Text != "")
            capTpiLabelData2.ContourDepth = result2;
          bool? isChecked = this.isTool.IsChecked;
          if (isChecked.HasValue)
          {
            CApTPILabelData capTpiLabelData3 = capTpiLabelData2;
            isChecked = this.isTool.IsChecked;
            int num = isChecked.Value ? 1 : 0;
            capTpiLabelData3.IsTool = num != 0;
          }
        }
      }
    }
  }

  private List<CApTPILabelData> SelectedItems
  {
    get
    {
      List<CApTPILabelData> selectedItems = new List<CApTPILabelData>();
      foreach (object selectedItem in (IEnumerable) this.myDataGrid.SelectedItems)
        selectedItems.Add(selectedItem as CApTPILabelData);
      return selectedItems;
    }
  }

  private List<ITxObject> SelectedApplicationObjects
  {
    get
    {
      return ((IEnumerable<ITxObject>) TxApplication.ActiveSelection.GetFilteredItems((ITxTypeFilter) new TxTypeFilter(typeof (ITxComponent)))).ToList<ITxObject>();
    }
  }

  private ITxComponent GetObjectByName(string name, TxObjectList objs)
  {
    return ((IEnumerable<ITxObject>) objs).Where<ITxObject>((Func<ITxObject, bool>) (x => x.Name == name)).FirstOrDefault<ITxObject>() as ITxComponent;
  }

  private void MyDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
  {
    Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
    try
    {
      TxApplication.ActiveSelection.Clear();
      if (this.myDataGrid.SelectedItem is CApTPILabelData selectedItem1)
      {
        this.labelName.Text = selectedItem1.Label;
        this.assemblyComponentType.Text = selectedItem1.AssemblyComponentType;
        this.contoursCount.Text = selectedItem1.NumberOfContours.ToString();
        this.contourDepth.Text = selectedItem1.ContourDepth.ToString();
        this.isTool.IsChecked = new bool?(selectedItem1.IsTool);
      }
      this._viewModel.GraphicsDrawer.Clear();
      this._viewModel.RefreshButtonState(this.myDataGrid.SelectedItems.Count, this.SelectedApplicationObjects.Count);
      if (!this._viewModel.PreviewContour)
        return;
      foreach (CApTPILabelData selectedItem2 in (IEnumerable) this.myDataGrid.SelectedItems)
        this._viewModel.ShowContour(selectedItem2);
    }
    finally
    {
      Mouse.OverrideCursor = (System.Windows.Input.Cursor) null;
    }
  }

  private void ActiveSelection_Changed(object sender, EventArgs args)
  {
    this._viewModel.RefreshButtonState(this.myDataGrid.SelectedItems.Count, this.SelectedApplicationObjects.Count);
  }

  private void TxWindow_Closed(object sender, EventArgs e)
  {
    TxApplication.ActiveSelection.Changed -= new TxSelection_ChangedEventHandler(this.ActiveSelection_Changed);
    this.StoreStringCollectionData("LabelsData", this._viewModel.LabelsData);
    this.StoreStringCollectionData("AssemblyComponentData", this._viewModel.AssemblyComponentData);
    this._viewModel.ClearData();
  }

  [DebuggerNonUserCode]
  [GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
  public void InitializeComponent()
  {
    if (this._contentLoaded)
      return;
    this._contentLoaded = true;
    System.Windows.Application.LoadComponent((object) this, new Uri("/DnProcessSimulateCommands;component/toolpositioninginternal/contours/cuitpigeneratecontoursdatasetwindow.xaml", UriKind.Relative));
  }

  [DebuggerNonUserCode]
  [GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
  [EditorBrowsable(EditorBrowsableState.Never)]
  void IComponentConnector.Connect(int connectionId, object target)
  {
    switch (connectionId)
    {
      case 1:
        ((Window) target).Closed += new EventHandler(this.TxWindow_Closed);
        break;
      case 2:
        ((System.Windows.Controls.Primitives.ButtonBase) target).Click += new RoutedEventHandler(this.BrowseButton_Click);
        break;
      case 3:
        this.labelName = (System.Windows.Controls.ComboBox) target;
        break;
      case 4:
        this.assemblyComponentType = (System.Windows.Controls.ComboBox) target;
        break;
      case 5:
        this.contoursCount = (System.Windows.Controls.TextBox) target;
        break;
      case 6:
        this.contourDepth = (System.Windows.Controls.TextBox) target;
        break;
      case 7:
        this.isTool = (System.Windows.Controls.CheckBox) target;
        break;
      case 8:
        ((System.Windows.Controls.Primitives.ButtonBase) target).Click += new RoutedEventHandler(this.InsertSelection_Click);
        break;
      case 9:
        this.myDataGrid = (System.Windows.Controls.DataGrid) target;
        this.myDataGrid.SelectionChanged += new SelectionChangedEventHandler(this.MyDataGrid_SelectionChanged);
        break;
      case 10:
        ((System.Windows.Controls.Primitives.ButtonBase) target).Click += new RoutedEventHandler(this.RestoreState_Click);
        break;
      case 11:
        ((System.Windows.Controls.Primitives.ButtonBase) target).Click += new RoutedEventHandler(this.SaveState_Click);
        break;
      case 12:
        ((System.Windows.Controls.Primitives.ButtonBase) target).Click += new RoutedEventHandler(this.Start_Click);
        break;
      case 13:
        ((System.Windows.Controls.Primitives.ButtonBase) target).Click += new RoutedEventHandler(this.Stop_Click);
        break;
      default:
        this._contentLoaded = true;
        break;
    }
  }
}
